package com.fc.remoting.core;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fc.commons.JsonUtils;
import com.fc.remoting.logger.LogSystem;
import com.fc.remoting.logger.MonitorConfig;
import com.fc.remoting.logger.Monitorlogger;
import com.fc.remoting.message.RemotingMessage;
import com.fc.remoting.protocol.IProtocol;
import com.fc.remoting.protocol.RemotingTcpProtocol;

import io.netty.channel.Channel;

/**
 * Tcp请求任务
 * @author Administrator
 *
 */
public class RemotingTask implements Runnable,Serializable  {

	Logger log = LoggerFactory.getLogger(RemotingTask.class);
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JSONObject request = null;
	private RemotingTcpProtocol handler = null;
	private Channel channel = null;
	public RemotingTask(Channel channel,IProtocol handler,JSONObject request) {
		this.channel = channel;
		this.handler = (RemotingTcpProtocol) handler;
		this.request = request;
	}
	
	@Override
	public void run() {
		Object response = null;
		try{
			LogSystem.instance().protocolProcessBegin(log,channel, request);
			response = handler.doHandler(this.channel,request);
			if(response instanceof RemotingMessage){
				channel.writeAndFlush(response);
			}else if(response != null){
				RemotingMessage message = RemotingMessage.createMessageInDefaultHeader(JsonUtils.object2Bytes(response));
				channel.writeAndFlush(message);
			}
			LogSystem.instance().protocolProcessComplete(log,channel,response,null);
//			if(response==null || !((JSONObject)response).get("code").equals("1")){
//				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.handleModule, MonitorConfig.fail,null,request,response);
//			}
		}catch(Exception e){
			LogSystem.instance().protocolProcessComplete(log,channel,null,e);
		}
	}
}
